package com.zz.yt.lib.login.popup;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.zz.yt.lib.login.R;
import com.zz.yt.lib.login.checker.FingerManager;
import com.zz.yt.lib.ui.popup.view.base.BaseCenterPopup;

import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;

import javax.crypto.KeyGenerator;

/**
 * 提示开通指纹登录
 *
 * @author qf
 * @version 22.4.22
 */
@SuppressLint("ViewConstructor")
public final class FingerPopup extends BaseCenterPopup {

    private final View.OnClickListener mClickListener;

    public static void create(View.OnClickListener listener) {
        new FingerPopup(listener).popup();
    }

    public FingerPopup(View.OnClickListener listener) {
        super(Latte.getActivity());
        this.mClickListener = listener;
    }

    @Override
    protected int setLayout() {
        return R.layout.hai_popup_finger;
    }

    @Override
    protected void initViews() {
        setOnClickListener(R.id.id_text_close, v -> dismiss());
        setOnClickListener(R.id.id_text_open, v -> initKey());
    }

    @TargetApi(23)
    private void initKey() {
        try {
            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
            keyStore.load(null);
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(FingerManager.DEFAULT_KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setUserAuthenticationRequired(true).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
            keyGenerator.init(builder.build());
            keyGenerator.generateKey();
            FingerManager.setFinger(true);
            dismiss();
        } catch (InvalidAlgorithmParameterException e) {
            ToastUtils.showShort("开通失败，您当前设备未设置指纹");
            dismiss();
        } catch (Exception e) {
            ToastUtils.showShort("开通失败，" + e.getMessage());
            dismiss();
        }
    }

    @Override
    public void dismiss() {
        if (mClickListener != null) {
            mClickListener.onClick(null);
        }
        super.dismiss();
    }
}
